import {
	login,
	logout
} from '@/api/user'

const getDefaultState = () => {
	return {
		name: '',
		avatar: '',
		roles: []
	}
}

const state = getDefaultState()

const mutations = {
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState())
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
	}
}

const actions = {
	// user login
	login({
		commit
	}, userInfo) {
		const {
			username,
			password
		} = userInfo
		return new Promise((resolve, reject) => {
			login({
				perAccount: username.trim(),
				perPasswd: password
			}).then(response => {
        commit('SET_NAME', username)
        sessionStorage.setItem('USERNAME', response.data.perName)
				// const { data } = response
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	logout({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			const data = sessionStorage.getItem('USERACCOUNT')
			logout({
				userAccount: data
			}).then(() => {
				sessionStorage.removeItem('PERTYPE')
        sessionStorage.removeItem('username')
				sessionStorage.removeItem('USERID')
        sessionStorage.removeItem('USERACCOUNT')
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
